#region File Header
//----------------------------------------------------------------
// Copyright (C) 2002 Stefan Kyntchev
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY 
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR 
// FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------
#endregion File Header

using System;
using System.IO;
using System.Collections;

namespace AirWeb.DirectoryMgr
{
	public enum CompareBy
	{
		None,
		Name,
		CreationDate,
		ModificationDate
	};

	public enum SortOrder
	{
		Ascending,
		Descending
	}

	public class FileComparer : IComparer
	{
		public FileComparer()
		{
			m_CompareBy = CompareBy.None;
			m_invert = false;
		}

		public FileComparer(CompareBy i_cb, SortOrder i_so)
		{
			m_CompareBy = i_cb;
			Sort = i_so;
		}

		private CompareBy m_CompareBy;
		private bool m_invert;

		public CompareBy compareBy
		{
			set
			{
				m_CompareBy = value;
			}

			get
			{
				return m_CompareBy;
			}
		}

		public SortOrder Sort
		{
			set
			{
				if(value == SortOrder.Ascending)
					m_invert = true;
				else
					m_invert = false;
			}
		}

		public int Compare(object A, object B)
		{
			FileSystemInfo a = (FileSystemInfo)A;
			FileSystemInfo b = (FileSystemInfo)B;

			int retVal = 0;
			
			switch(m_CompareBy)
			{
				case CompareBy.CreationDate:
					if(a.CreationTime > b.CreationTime)
					{
						retVal = 1;
					}
					else if(a.CreationTime == b.CreationTime)
					{
						retVal = 0;
					}
					else
					{
						retVal = -1;
					}
					break;

				case CompareBy.ModificationDate:
					if(a.LastWriteTime > b.LastWriteTime)
					{
						retVal = 1;
					}
					else if(a.LastWriteTime == b.LastWriteTime)
					{
						retVal = 0;
					}
					else
					{
						retVal = -1;
					}
					break;

				case CompareBy.Name:
					retVal = Comparer.Default.Compare(a.Name,b.Name);
					break;

				case CompareBy.None:
					retVal = 0;  // Don't sort
					break;

				default:	
					throw new ArgumentException("Invalid comparison type","m_CompareBy");
			}

			// Invert the result. This has the effect of switching ascending and descending order
			if(m_invert)
			{
				if(retVal == -1)
				{
					retVal = 1;
				}
				else if(retVal == 1)
				{
					retVal = -1;
				}
			}
			
			return retVal;
		}
	}
}
